var subMenuList = [];
var form;
$(document).ready(function () {
  Judgeidentity();
  initSize();
  // initMenu()
  //获取当前时间
  // $("#time").showCurrentTime();
  getMainMenu();
  initWebSocket();

  initEvent();
});

// 初始化顶部菜单
function getMainMenu() {
  AjaxRequest('/menu/auth', callBack);

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;
      var str = '';

      $.each(data, function (i, e) {
        if (!e.pId) {
          var active = '';
          var curPath = window.location.href;
          if (curPath.indexOf(e.path) > -1 && e.path != '/') {
            active = 'active';
          } else {
            active = '';
          }
          str += `<div class="header-menu-item ${active}" onclick='turnPage(${JSON.stringify(e)})'>
                      <span>${e.name}</span>
                  </div>`;
        } else {
          subMenuList.push(e);
        }
      });
      $('.header-menu').empty().append(str);

      if ($('.menu-list').length > 0) {
        getSubMenu();
      }


    }
  }
}

function turnPage(obj) {
  if (obj.path != '/') {
    window.location.href = '../html/' + obj.path;
  } else if (obj.name == '基础管理') {
    window.location.href = '../html/' + subMenuList[0].path;
  }
}

function getSubMenu() {
  var str = '';
  $.each(subMenuList, function (i, e) {
    var active = '';
    var curPath = window.location.href;
    if (curPath.indexOf(e.path) > -1 && e.path != '/') {
      active = 'active';
    } else {
      active = '';
    }
    str += `<li class="list-item ${active}" onclick='turnPage(${JSON.stringify(
      e
    )})'>
                    <img src="../static/img/${e.icon}">
                    <span>${e.name}</span>
                </li>`;
  });
  $('.menu-list').empty().append(str);
  $('.header-menu-item')
    .eq(6)
    .addClass('active')
    .siblings()
    .removeClass('active');
}

/*初始化默认字体大小*/
function initSize() {

  $(document).ajaxSuccess(function (event, xhr, options, exc) {

    if (JSON.parse(xhr.responseText).status == 401) {

      loginOut()
      return
    }

  })


  //适应不同分辨率
  let fontSize;
  resize();
  window.onresize = resize;

  function resize() {
    let winW = window.innerWidth;

    if (winW < 1366) {
      winW = 1366;
    }
    fontSize = (winW / 1920) * 100;
    document.getElementsByTagName('html')[0].style.cssText =
      'font-size:' + fontSize + 'px';
  }
}

// 顶部菜单切换
// $('.header-menu-item').click(function (e) {
//     $(e.currentTarget).addClass('active').siblings().removeClass('active');
// })

// 侧边栏菜单
initSubMenu = () => {
  var data = [];

  $('.contain-menu')
    .empty()
    .append(
      data.reduce((x, y) => {
        var active = '';

        if (window.location.href.indexOf(y.href) > -1) {
          active = 'active';
        } else {
          active = '';
        }

        return (
          x +
          `<div class="menu-item ${active}" onclick=checkSubMenu("${y.href}")>
                    <img src="../static/img/menu${y.type}.png">${y.name}
                </div>`
        );
      }, '')
    );
};

// 侧边菜单切换
function checkSubMenu(href) {
  window.location.href = '../html/' + href + '.html';
}

/*判断字段是否为空或者*/
function checkNullOrEmpty(field) {
  if (field == null || field === '') {
    return '';
  } else {
    return field;
  }
}

/**/

function logout() {
  layer.confirm(
    '确定退出系统？',
    {
      btn: ['确定', '取消'], //按钮
    },
    function () {
      loginOut();
    }
  );
}

function loginOut() {
  $.ajax({
    url: '/rest/jxsh/logout',
    type: 'post',
    contentType: 'application/json',
    success: function (result) {
      localStorage.setItem('sessionId', '');

      window.location.href = '../html/login.html';
    },
    error: function (result) {
      localStorage.setItem('sessionId', '');
      window.location.href = '../html/login.html';
    },
  });
}

function Judgeidentity() {
  var isLogin = localStorage.getItem('sessionId');
  if (isLogin == null || isLogin == '') {
    window.location.href = '../html/login.html';
  }
}

function ajaxPrefix() {
  return '/rest/jxsh';
}

function Ajax(url, callBack, parms, type) {
  $.ajax({
    url: ajaxPrefix() + url,
    type: type ? type : 'get',
    data: parms ? JSON.stringify(parms) : '',
    headers: {
      SessionId: JSON.parse(localStorage.getItem('sessionId')),
    },
    contentType: 'application/json',
    success: function (result) {
      callBack(result);
    },
  });
}

function AjaxRequest(url, callBack, parms, type, async) {
  $.ajax({
    url: ajaxPrefix() + url,
    type: type ? type : 'get',
    data: parms ? JSON.stringify(parms) : '',
    traditional: true,
    headers: {
      SessionId: JSON.parse(localStorage.getItem('sessionId')),
    },
    contentType: 'application/json',
    success: function (result) {
      callBack(result);
    },
  });
}

// 获取某天前几天方法
function getBeforeDate(num) {
  var date1 = new Date();
  //今天时间
  var time1 =
    date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate();
  var date2 = new Date(date1);
  date2.setDate(date1.getDate() + num);
  //num是正数表示之后的时间，num负数表示之前的时间，0表示今天
  var time2 =
    addZero(date2.getFullYear()) +
    '-' +
    addZero(date2.getMonth() + 1) +
    '-' +
    addZero(date2.getDate());
  return time2;
}

//补0方法
function addZero(num) {
  if (parseInt(num) < 10) {
    num = '0' + num;
  }
  return num;
}

function showPhotoWindow(time, filePath) {
  layer.photos({
    photos: {
      title: '', //相册标题
      id: 123, //相册id
      start: 0, //初始显示的图片序号，默认0
      data: [
        //相册包含的图片，数组格式
        {
          alt: '',
          pid: time, //图片id
          src: '/images/' + filePath, //原图地址
          thumb: '', //缩略图地址
        },
      ],
    },
    anim: 5, //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
  });
}
// 获取当前年月
getMonth = () => {
  let timestamp = Date.parse(new Date());
  let date = new Date(timestamp);
  //获取年份
  let thisYear = date.getFullYear();

  // 获取月份
  let thisMonth = date.getMonth() + 1; // 返回值为1-12之间的整数

  // 将月份值转换为带有前导零的文本形式
  let formattedMonth = thisMonth.toString().padStart(2, '0');

  return thisYear + '-' + formattedMonth;
};

var tryTime;

function initWebSocket() {


  if (!window.WebSocket) {
    return false;
  }

  let domain = window.location.host.split(':')[0];

  // webSocket = new WebSocket("ws://dev.njdtwise.com/rest/ts/websocket/" + localStorage.getItem('orgId'));
  webSocket = new WebSocket(
    'ws://' + domain + ':9114/websocket/' +
    localStorage.getItem('orgId')
  );

  webSocket.onopen = function (evt) {
    tryTime = 0;
  };

  webSocket.onmessage = function (msg) {
    msg = eval('(' + msg.data + ')');
    // console.log(msg);

    if (msg.data == '&' || msg.appid == 3) {
    } else {

      if (msg.dataType == 1 || msg.dataType == 2) {

        // 3 开关 4 本地丨远程  oilStatus 0-关闭1-打开  1-手动 0-自动
        //  valveStatus
        if (window.location.href.indexOf('index.html') > -1) {
          $('#status-change').empty().append(`
            <div class="status-item">
                <img src="../static/img/valve.png" alt="">
                <div>阀门名称</div>
                <div class="status-data">${msg.valveName}</div>
            </div>
            <div class="status-item">
                <img src="../static/img/gateway.png" alt="">
                <div>阀门编号：</div>
                <div class="status-data">${msg.valveCode}</div>
            </div>
            <div class="status-item">
                <img src="../static/img/status.png" alt="">
                <div>状态变化：</div>
                <div class="status-data">${msg.valveStatusDesc}</div>
            </div>
            <div class="status-item">
                <img src="../static/img/datetime.png" alt="">
                <div>上报时间：</div>
                <div class="status-data">${msg.dataTime}</div>
            </div>
            <div class="status-item">
                <img src="../static/img/oiltank.png" alt="">
                <div>所属油罐：</div>
                <div class="status-data">${msg.oilName}</div>
            </div>
`)

          queryDeviceData()

          $('.log-check>div').eq(0).click()

          changeOilColor(msg)


        } else if (window.location.href.indexOf('realtimedata.html') > -1) {
          $('#submit-search').click();
        }



        layer.open({
          title:
            '<span style="color:#ff7145;font-weight:bold;margin-right: 10px;">警告</span><i style="color: #ff7145;" class="fa fa-bullhorn"></i>',
          type: 1,
          offset: 'rb',
          move: false,
          content: `
                    <div class="websorket-body">
                        <ul>
                            <li><div><span>阀门名称：</span>${msg.valveName}</div></li>
                            <li><div><span>阀门编号：</span>${msg.valveCode}</div></li>
                            <li><div><span>状态变化：</span>${msg.valveStatusDesc}</div></li>
                            <li><div><span>上报时间：</span>${msg.dataTime}</div></li>
                            <li><div><span>所属油罐：</span>${msg.oilName}</div></li>
                        </ul>
                        <audio autoplay="autoplay"><source src="../static/img/video/fire.mp3" type="audio/mpeg"><source src="../static/img/video/fire.ogg" type="audio/ogg"></audio>
                </div>`,
          shade: 0, //不显示遮罩
        });



      } else {
        if (msg.dataType == 3) {// 3 开关 

          if (msg.oilStatus == 1) {// oilStatus 0-关闭1-打开
            $('#label-ss-' + msg.oilCode).show()
          } else {
            $('#label-ss-' + msg.oilCode).hide()
          }
        } else if (msg.dataType == 4) {//4 本地丨远程
          if (msg.oilStatus == 0) {// oilStatus 0-关闭1-打开
            $('#label-ma-' + msg.oilCode).show()
          } else {
            $('#label-ma-' + msg.oilCode).hide()
          }
        }


        //    1-手动 0-自动

        // queryOilStatus()
      }

      if ($('.map-window').css('display') == 'block' && ($('.window-title').html().split('：')[1] == msg.oilName)) {
        queryOilValve(msg.oilCode)
      }


    }
  };

  webSocket.onerror = function (evt) { };

  webSocket.onclose = function () {
    // 重试2次，每次之间间隔2秒
    if (tryTime < 4) {
      setTimeout(function () {
        webSocket = null;
        tryTime++;
        initWebSocket();
      }, 5 * 1000);
    } else {
    }
  };
}

function closeWebSocket() {
  if (webSocket) {
    webSocket.close();
  }
}

function showPasswordWindow() {
  layer.open({
    type: 1,
    title: '修改密码',
    skin: 'default-class',
    area: ['4.5', 'auto'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<form class="layui-form" style="margin: .3rem;height:calc(100% - .6rem)">
                <div class="layui-form-item">
                  <label class="layui-form-label">新密码</label>
                  <div class="layui-input-block">
                    <input type="password" name="passwordOne" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <input type="hidden" name="id" autocomplete="off" class="layui-input">
                <div class="layui-form-item">
                  <label class="layui-form-label">确认密码</label>
                  <div class="layui-input-block">
                    <input type="password" name="passwordTwo" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align:center">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="savePassword">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
    success: function (layero, index) { },
  });
}

function initEvent() {
  layui.use(function () {
    form = layui.form;

    form.on('submit(savePassword)', function (data) {
      AjaxRequest(
        '/user/password/update',
        callBack,
        {
          id: JSON.parse(localStorage.getItem('userInfo')).userId,
          passwordOne: data.field.passwordOne,
          passwordTwo: data.field.passwordTwo,
        },
        'post'
      );

      function callBack(result) {
        if (result.status == 200) {
          layer.closeAll();
          layer.msg('修改成功，3秒后返回登录页！');
          setTimeout(() => {
            loginOut();
          }, 3000);
        } else {
          layer.msg(result.result + '！');
        }
      }
      return false;
    });
  });
}


// 开关操作
deviceOp = (id, type) => {

  layer.confirm(
    '确定' + (type == 0 ? '关闭' : '打开') + '阀门吗',
    {
      btn: ['确定', '取消'], //按钮
    },
    function () {

      AjaxRequest('/valve/ss/operate/down', Callback, { id: id, ssStatus: type }, 'post')

      function Callback(result) {

        if (result.message == "OK") {
          layer.msg('操作成功')
        } else {
          layer.msg('下发失败')
        }


      }

    }
  );

}
// 查询油罐阀门
queryOilValve = (name) => {
  name = name.split('-')[0] + '-' + name.split('-')[1];
  AjaxRequest('/valve/list?pageNum=1&pageSize=10&oilCode=' + name, Callback)

  function Callback(result) {
    var data = result.result.data;

    $('.window-title').html('油罐：' + name)

    $('.window-table').empty().append(data.reduce((x, y) => {
      let disabled;


      if (y.maStatus == 0) {
        disabled = 2;
      } else {
        if (y.ssStatus == 1) {
          disabled = 0;
        } else if (y.ssStatus == 0) {
          disabled = 1;
        }

      }

      switch (y.seqNo) {
        case 1:
          var ds = '左上'

          break;
        case 2:
          var ds = '左下'

          break;
        case 3:
          var ds = '右下'

          break;
        case 4:
          var ds = '右上'

          break;

        default:
            var ds = ''
          break;
      }

      return x +
        `<div class="window-table-item">
              <div style="color: #82E7FF;">${y.name}</div>
              <div style="color: #82E7FF;">${ds}</div>
              <div style="color:${y.ssStatus == 0 ? '' : '#FFE746'}">${y.ssStatusDesc}</div>
              <div style="color:${y.maStatus == 1 ? '' : '#FF2D2D'}">${y.maStatusDesc}</div>
              <div><div onclick=deviceOp("${y.id}",1) class="window-table-item-button ${(disabled == 0 || disabled == 2) ? 'prohibitClick' : ''} start">打开</div></div>
              <div><div onclick=deviceOp("${y.id}",0) class="window-table-item-button ${(disabled == 1 || disabled == 2) ? 'prohibitClick' : ''} stop">关闭</div></div>
          </div>
          `
    }, `<div class="window-table-item">
              <div>名称</div>
              <div>位置</div>
              <div>阀门开关</div>
              <div>本地丨远程状态</div>
              <div>操作</div>
              <div>操作</div>
          </div>`))
    $('.map-window').show();


  }


}


// 刷新油罐状态
queryOilStatus = () => {
  AjaxRequest('/oiltank/list?pageNum=1&pageSize=100', callback)
  function callback(res) {
    let code = res.status;
    if (code != 200) {
      return;
    }

    res.result.data.forEach(e => {
      // ma 本地远程  0是本地 1是远程
      // ss 打开关闭  0是关闭 1是打开
      if (e.maStatus == 0) {
        $('#label-ma-' + e.code).show()
      }

      if (e.ssStatus == 1) {
        $('#label-ss-' + e.code).show()
      }

    });

  }
}
